<?php
App::uses('AppController', 'Controller');
/**
 * Films Controller
 *
 * @property Film $Film
 */
class FilmsController extends AppController {
var $uses=array('Film','Tag');
	public $paginate = array(
        'limit' => 6,
        'order' => array(
            'Film.calification' => 'desc'
        )
    );

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->Film->recursive = 0;
		$this->set('films', $this->paginate());
	}

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->Film->id = $id;
		if (!$this->Film->exists()) {
			throw new NotFoundException(__('Invalid film'));
		}
		$this->set('film', $this->Film->read(null, $id));
		require_once('servicio_web.php');
		$f=relacionadas($this->Film->data['Film']['title']);
		$related=array();
		$i=0;
		if(!empty($f))
		foreach ($f as $movie){
			if($aux=$this->Film->find('first',array('fields' => array('id','title'),'recursive'=>'-1','conditions' => array('title' => $movie['title'])))){
				$related[$i]=array('exist'=>'1','title'=>$aux['Film']['title'],'id'=>$aux['Film']['id']);
				$i++;
			}else{
				$related[$i]=array('title'=>$movie['title'],'id'=>$movie['id'],'exist'=>'0');
				$i++;
			}
		}
		$this->set('related',$related);
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->Film->create();
			if(empty($this->request->data['Film']['Image'])){
				if(!empty($this->request->data['Film']['Imagen']['name']))
					$this->request->data['Film']['Image']=$this->request->data['Film']['Imagen']['name'];
				else
					$this->request->data['Film']['Image']='no_image.jpg';
			}
			$f=$this->Film->save($this->request->data);
			if(in_array($this->request->data['Film']['Imagen']['error'], array(0, 4)) && $f){
				if($this->request->data['Film']['Imagen']['error'] == 0){
					$path = '../webroot/img/';
					if(!@opendir($path)){
						mkdir($path);
					}
					move_uploaded_file($this->request->data['Film']['Imagen']['tmp_name'], $path.$this->request->data['Film']['Imagen']['name']);
				}
			}
			
			if($this->request->data['Film']['calificacion_total']!=0)
				$this->request->data['Film']['cant_votantes']=1;

			if ($f) {
				$tags=explode('     ',$this->request->data['Film']['newTags']);
				foreach($tags as $tag){
					if(!empty($tag)){
						$t=array();
						$t['Tag']=array();
						$t['Tag']['film_id']=$f['Film']['id'];
						$t['Tag']['tag']=$tag;
						$this->Tag->create();
						$this->Tag->save($t);
					}
				}
				$this->Session->setFlash(__('The film has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The film could not be saved. Please, try again.'));
			}
		}
		$actors = $this->Film->Actor->find('list');
		$directors = $this->Film->Director->find('list');
		$genres = $this->Film->Genre->find('list');
		$rFilms = $this->Film->RFilm->find('list');
		$this->set(compact('actors', 'directors', 'genres','rFilms'));
	}

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->Film->id = $id;
		if (!$this->Film->exists()) {
			throw new NotFoundException(__('Invalid film'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$tags=explode('     ',$this->request->data['Film']['newTags']);
			foreach($tags as $tag){
				if(!empty($tag)){
					$t=array();
					$t['Tag']=array();
					$t['Tag']['film_id']=$this->request->data['Film']['id'];
					$t['Tag']['tag']=$tag;
					$this->Tag->create();
					$this->Tag->save($t);
					var_dump($t);
				}
			}
			if ($this->Film->save($this->request->data)) {
				$this->Session->setFlash(__('The film has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The film could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->Film->read(null, $id);
		}
		$actors = $this->Film->Actor->find('list');
		$directors = $this->Film->Director->find('list');
		$genres = $this->Film->Genre->find('list');
		$rFilms = $this->Film->RFilm->find('list');
		$this->set(compact('actors', 'directors', 'genres','rFilms'));
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Film->id = $id;
		if (!$this->Film->exists()) {
			throw new NotFoundException(__('Invalid film'));
		}
		if ($this->Film->delete()) {
			$this->Session->setFlash(__('Film deleted'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Film was not deleted'));
		$this->redirect(array('action' => 'index'));
	}
	
	public function calificar($id=null){
		$this->layout='ajax';
		$calificacion=$this->data['calificacion'];
		$data=$this->Film->find('first',array('fields' => array('id','cant_votantes','calificacion_total'),'recursive'=>'-1','conditions' => array('id' => $id)));
		$data['Film']['cant_votantes']++;
		$data['Film']['calificacion_total']+=$calificacion;
		$this->Film->save($data);
		$promedio=$data['Film']['calificacion_total']/$data['Film']['cant_votantes'];
		$this->set('calificacion',(int)$promedio);
	}
	public function cargar($nombre=null){
		$this->layout='ajax';
		$datosRelacionadas = relacionadas2($this->data['Film']['title'],$this);
		$this->set('datosRelacionadas',$datosRelacionadas);
		
	}
	

	
}



function datosPelicula($titulo){
		$apikey = 'evp42bcxmcj6j2pnggapcwvt';
		$q = urlencode($titulo); // make sure to url encode an query parameters
		// construct the query with our apikey and the query we want to make
		$endpoint = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey='.$apikey.'&q='.$q.'&page_limit=1';
		// setup curl to make a call to the endpoint
		$session = curl_init($endpoint);
		// indicates that we want the response back
		curl_setopt($session,CURLOPT_RETURNTRANSFER,true);
		// exec curl and get the data back
		$data = curl_exec($session);
		// remember to close the curl session once we are finished retrieveing the data
		curl_close($session);
		return $data;
	}
function relacionadas2($pelicula, $controlador)
{
	$apikey = 'evp42bcxmcj6j2pnggapcwvt';
	$q = urlencode($pelicula); // make sure to url encode an query parameters
	// construct the query with our apikey and the query we want to make
	$endpoint = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey='.$apikey.'&q='.$q;
	// setup curl to make a call to the endpoint
	$session = curl_init($endpoint);
	// indicates that we want the response back
	curl_setopt($session,CURLOPT_RETURNTRANSFER,true);
	// exec curl and get the data back
	$data = curl_exec($session);
	// remember to close the curl session once we are finished retrieveing the data
	curl_close($session);
	// decode the json data to make it easier to parse the php
	$search_results = json_decode($data);
	if ($search_results === NULL) 
	{
		return null;
	}
	$total=$search_results->total;
	if(count($search_results->movies)==0)
		{
			$todoDatos=array();
			$data= array("total" => $total);
			$todoDatos[0]=$data;
			return json_encode($todoDatos);
		}
	// play with the data!
	if ($total>0){
		$movies = $search_results->movies;	
		$movie=$movies[0];
		
		//$total=$movies->total;
		$id=$movie->id;
		$title=$movie->title;
		$synopsis=$movie->synopsis;
		$runtime=$movie->runtime;
		$year=$movie->year;
		$imagen=$movie->posters->original;
		$calificacion=$movie->ratings->critics_score==-1?0:(int)($movie->ratings->critics_score/10);
		
		$todoDatos=array();
		$data= array("total" =>$total, "titulo" => $title, "synopsis" => $synopsis, "runtime" => $runtime,"year" => $year, "imagen" => $imagen, "calificacion"=>$calificacion);
		$todoDatos[0]=$data;
		
		$relacionadas=$movie->links->similar;
		$relacionadas=$relacionadas.'?apikey='.$apikey.'&limit=5';
		//var_dump($relacionadas);
		
		$session2 = curl_init($relacionadas);
		curl_setopt($session2,CURLOPT_RETURNTRANSFER,true);
		$data2 = curl_exec($session2);
		curl_close($session2);
		$search_results2 = json_decode($data2);
		if ($search_results2 === NULL) 
			{die('Error parsing json');return;}
		$movies = $search_results2->movies;
		
		$peliculas = array(); //las peliculas relacionadas que no estan en la BD
		$peliculas2 = array(); //las peliculas relacionadas que si estan en la BD
		$cont=0;
		$cont2=0;
		foreach ($movies as $movie){
			if($aux=$controlador->Film->find('first',array('fields' => array('id','title'),'recursive'=>'-1','conditions' => array('title' => $movie->title)))){
				$peliculas2[$cont2++]=array('title'=>$aux['Film']['title'],'id'=>$aux['Film']['id']);
			}else{
				$peliculas[$cont]=array('title'=>$movie->title,'id'=>$movie->id);
				$cont=$cont+1;
			}
		}
		$todoDatos[1]=$peliculas;
		$todoDatos[2]=$peliculas2;
	}
	
	return json_encode($todoDatos);
}	